<template>
  <div class="car_container">
    <el-upload
        class="avatar-uploader"
        name="file"
        :show-file-list=false
        drag
        :action="$url+'/upload'"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" alt=""/>
      <div v-else class="el-upload__text">
        <el-icon class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
        <p>将图片拖到此处或<em>点击上传图片</em></p>
      </div>
    </el-upload>
    <div style="width: 50%">
      <span :class="['span-message', animateClass]">{{ message }}</span>
      <el-progress
          :percentage="percentage"
          :stroke-width="15"
          :status="status"
          :duration=duration>
      </el-progress>
    </div>
    <div class="showCar">
      <span :class="['showCarMess',animateCarMessClass]">{{ showCarMess }}</span>
      <n-image
          width="200"
          :src="showImg"
      />
    </div>
  </div>
  <div class="space">
    <Step :list="showStepImg"></Step>
  </div>

</template>

<script lang="ts" setup>
import {computed, ref } from "vue";
import type {UploadProps} from 'element-plus'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import axios from "axios";
import {useAnimatedWatcher} from '@/hooks/useAnimatedWatcher.ts';
import Step from "@/components/Step/index.vue"

const percentage = ref<number>(0)
const duration = computed(() => Math.floor(percentage.value / 10))
let showImg = ref('')
const imageUrl = ref('')

let message = ref('')
let status = ref<any>('success')
let showCarMess = ref('')
let active = ref(0)
let $url = "https://python.xuxiao888.com"
// let $url = " http://127.0.0.1:5000"
let showStepImg = ref<any>([])
//监听message的动画
const animateClass = useAnimatedWatcher(message, 'animate-fade', 700);
const animateCarMessClass = useAnimatedWatcher(showCarMess, 'animateCarMessClass', 700);

const handleAvatarSuccess: UploadProps['onSuccess'] = async (response, uploadFile) => {
  // console.log(JSON.parse(response.result))
  percentage.value = 100
  message.value = response.message
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  if (response.code == 500) {
    // message.value = response.message
    status.value = 'exception'

    ElMessageBox.confirm("是否启用深度识别", '图片识别失败', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      let text = JSON.parse(response.result).words_result.number
      setTimeout(() => {
        ElMessageBox.alert(text, '识别结果', {
          type: 'success',
          confirmButtonText: 'OK',
        })
      }, 1000)
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '该图片不包含车牌号码',
      })
    })
  } else {
    status.value = "success"
    showCarMess.value = "原图"
    let showCar: any = document.querySelector(".showCar")
    showCar.style.border = "none"
    showImg.value = URL.createObjectURL(uploadFile.raw!)

    showStepImg.value.push({
      img: showImg.value,
      title: "原图"
    })
    active.value++
    console.log(showStepImg.value)
    let id = response.filename.split('.')[0]
    await handleStep(id, "去噪", "one", "滤波结果（去噪）", "去噪")
    await handleStep(id, "色彩空间转换（RGB-->GRAY)", "two", "灰度图", "灰度图")
    await handleStep(id, "Sobel算子（X方向边缘梯度）", "three", "图像边缘图", "X方向边缘梯度")
    await handleStep(id, "阈值", "four", "阈值处理图", "阈值处理")
    await handleStep(id, "闭运算：先膨胀后腐蚀", "five", "闭运算处理图", "闭运算")
    await handleStep(id, "开运算：先腐蚀后膨胀", "six", "开运算处理图", "开运算")
    await handleStep(id, "中值滤波：去除噪声", "seven", "中值滤波处理图", "中值滤波", true)
    await handleStep(id, "轮廓车牌", "eight", "轮廓车牌结果", "轮廓车牌")
    await handleStep(id, "逐个遍历，将宽度>3倍高度的轮廓确定为车牌", "nine", "车牌结果", "车牌")
    await resultCarPlate(id)
  }
}
const handleStep = async (id: any, stepName: string, apiEndpoint: string, nextStepMessage: string, endName: string, isOver: boolean = false) => {
  await new Promise((resolve) => {
    setTimeout(resolve, 1000)
  })
  percentage.value = 0
  message.value = `正在${stepName}处理`;
  await new Promise((resolve) => {
    setTimeout(async () => {
      try {
        let response = await axios.get(`${$url}/${apiEndpoint}/?id=${id}`, {
          responseType: 'blob'
        });
        showImg.value = URL.createObjectURL(response.data);
        showStepImg.value.push({
          img: showImg.value,
          title: nextStepMessage
        });
        percentage.value = 100;
        showCarMess.value = nextStepMessage;
        message.value = `${endName}处理成功`;
        active.value++; // 假设这是正确的逻辑
      } catch (error) {
        // 错误处理
        console.error(error);
        message.value = `${stepName}处理失败`;
      }
      resolve(); // 解析Promise
    }, 500)
  })
}
const resultCarPlate = async (id: any) => {
  await new Promise((resolve) => {
    setTimeout(resolve, 1000)
  })
  percentage.value = 0
  message.value = "正在识别车牌"
  return new Promise((resolve) => {
    setTimeout(async () => {
      let data2: any = await axios.get(`https://python.xuxiao888.com/ten/?id=${id}`)
      percentage.value = 100
      showCarMess.value = "识别车牌结果"
      message.value = "车牌识别成功"
      await ElMessageBox.alert(data2.data.message, '识别结果', {
        type: 'success',
        confirmButtonText: 'OK',
      })
    }, 2000)
  })
}

const beforeAvatarUpload: any = () => {
  console.log(active.value)
  if (active.value == 0 || active.value == 10) {
    showStepImg.value = []
    showImg.value = ""
    active.value = 0
  } else {
    ElMessage({
      message: '请等待',
      type: 'error',
      plain: true,
    })
    return false
  }
  return true
}
</script>
<style scoped>
.car_container {
  margin: 0 auto;
  width: 60%;
  height: 40vh;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader .avatar {
  width: 200px;
  display: block;
}

.space {
  display: flex;
  justify-content: center;
  align-items: center;
}

.showCar {
  border: 1px solid #000;
}

.showCarMess {
  display: block;
  width: 100%;
  text-align: center;
  font-family: Helvetica sans-serif;
  font-size: 20px;
  color: red;
  line-height: 25px
}

.span-message {
  display: block;
  width: 100%;
  text-align: center;
  color: #1bc055;
  font-family: Helvetica sans-serif;
  font-size: 20px;
  line-height: 25px;
}

.animateCarMessClass {
  animation: fade1 1s ease-in-out;

}

@keyframes fade1 {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.animate-fade {
  animation: fade 1s ease-in-out;
}

@keyframes fade {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>